// pages/exerciseAdd/exerciseAdd.js
const api = require('../../utils/api/index');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 运动类型数据
    exerciseTypes: [],
    exerciseTypeIcons: [],
    exerciseTypeIndex: 0,
    // 运动类别数据
    exerciseCategories: ["有氧运动", "抗阻训练", "柔韧与平衡"],
    inferredCategory: 0,
    categorizedExerciseTypes: [],
    // 添加一个loading状态
    loading: false,
    // 基本表单数据
    exerciseDate: '',
    startTime: '12:00',
    duration: 30,
    intensity: 5,
    caloriesBurned: '',
    enableGlucoseMonitoring: false,
    glucoseBefore: '',
    glucoseAfter: '',
    notes: '',
    // 编辑模式标识
    id: null,
    // 用户体重，用于卡路里计算
    weight: 65,
    // 用户完整资料
    age: 40,
    gender: 'male',
    height: 170,
    exerciseFrequency: 'occasional'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    // 设置当前日期为默认日期
    this.setCurrentDate();
    
    // 获取用户完整资料（包含体重、身高、年龄等）
    await this.getUserProfile();

    // 获取运动类型列表
    await this.getExerciseTypes();

    // 如果有options.id，说明是编辑模式，需要获取运动数据
    if (options.id) {
      this.setData({
        id: options.id
      });
      await this.getExerciseData(options.id);
    } else {
      // 新建模式，预计算默认卡路里消耗
      this.calculateCalories();
    }
  },

  /**
   * 获取用户体重数据
   */
  getUserWeight: async function() {
    try {
      // 尝试获取用户最新的健康数据
      const response = await api.health.getLatestHealthData();
      if (response && response.success && response.data && response.data.weight) {
        this.setData({
          weight: response.data.weight
        });
        // 重新计算卡路里
        this.calculateCalories();
      } else {
        console.log('未找到用户体重数据，使用默认值');
      }
    } catch (error) {
      console.error('获取用户体重失败:', error);
      // 使用默认体重，不做任何修改
    }
  },

  /**
   * 获取运动类型列表
   */
  getExerciseTypes: async function() {
    this.setData({ loading: true });
    try {
      const response = await api.exercise.getExerciseTypes();
      if (response.success && response.data) {
        // 将API返回的数据重新组织为分类格式
        const categorizedTypes = this.organizeCategorizedTypes(response.data);
        
        // 生成扁平化的类型列表，用于老版本兼容
        const allTypes = [];
        const allIcons = [];
        
        categorizedTypes.forEach(category => {
          category.types.forEach(type => {
            allTypes.push(type.name);
            allIcons.push(type.icon);
          });
        });
        
        this.setData({
          categorizedExerciseTypes: categorizedTypes,
          exerciseTypes: allTypes,
          exerciseTypeIcons: allIcons,
          loading: false
        });
        
        // 推断当前运动类别
        this.updateInferredCategory();
      }
    } catch (error) {
      console.error('获取运动类型失败:', error);
      // 加载默认的分类运动类型
      this.loadDefaultExerciseTypes();
      this.setData({ loading: false });
    }
  },
  
  /**
   * 组织分类的运动类型数据
   */
  organizeCategorizedTypes: function(apiData) {
    // 使用默认分类数据
    const categorizedTypes = [
      {
        category: "有氧运动",
        types: []
      },
      {
        category: "抗阻训练",
        types: []
      },
      {
        category: "柔韧与平衡",
        types: []
      }
    ];
    
    // 根据名称匹配分类
    apiData.forEach(item => {
      const name = item.name.toLowerCase();
      let categoryIndex = this.inferExerciseCategory(name);
      
      categorizedTypes[categoryIndex].types.push(item);
    });
    
    return categorizedTypes;
  },
  
  /**
   * 根据运动类型推断运动类别
   */
  inferExerciseCategory: function(exerciseName) {
    // 将运动名称转为小写以便匹配
    const name = typeof exerciseName === 'string' ? exerciseName.toLowerCase() : '';
    
    // 有氧运动关键词
    if (name.includes('走') || name.includes('跑') || name.includes('骑') || 
        name.includes('游泳') || name.includes('舞') || name.includes('椭圆') || 
        name.includes('跳绳') || name.includes('球类') || name.includes('爬楼梯') || 
        name.includes('有氧') || name.includes('健走') || name.includes('广场舞') ||
        name.includes('散步') || name.includes('慢走') || name.includes('快走') ||
        name.includes('踏板') || name.includes('划船')) {
      return 0; // 有氧运动
    } 
    // 抗阻训练关键词
    else if (name.includes('哑铃') || name.includes('弹力') || name.includes('举') || 
             name.includes('深蹲') || name.includes('俯卧') || name.includes('起坐') || 
             name.includes('力量') || name.includes('健身') || name.includes('推') || 
             name.includes('拉') || name.includes('重量') || name.includes('肌肉') ||
             name.includes('杠铃') || name.includes('器械') || name.includes('抗阻') ||
             name.includes('负重') || name.includes('壶铃') || name.includes('引体向上') ||
             name.includes('卧推') || name.includes('划船') || name.includes('蹲起')) {
      return 1; // 抗阻训练
    } 
    // 柔韧与平衡关键词
    else if (name.includes('拉伸') || name.includes('平衡') || name.includes('柔韧') || 
             name.includes('冥想') || name.includes('伸展') || name.includes('瑜伽') ||
             name.includes('八段锦') || name.includes('柔软') || name.includes('舒展')) {
      return 2; // 柔韧与平衡
    } 
    // 太极需要特殊处理，因为它既是有氧运动也是柔韧与平衡运动
    // 根据用户描述，我们将太极归类为有氧运动
    else if (name.includes('太极')) {
      return 0; // 太极归类为有氧运动
    }
    else {
      // 默认分类为有氧运动
      return 0;
    }
  },
  
  /**
   * 加载默认的运动类型数据
   */
  loadDefaultExerciseTypes: function() {
    // 这里使用预设的运动类型数据
    const exerciseTypesData = [
      {
        category: "有氧运动",
        types: [
          { name: "快走", icon: "🚶", met: 3.5 },
          { name: "慢跑", icon: "🏃", met: 7.0 },
          { name: "骑自行车", icon: "🚴", met: 6.0 },
          { name: "游泳", icon: "🏊", met: 6.0 },
          { name: "跳舞", icon: "💃", met: 4.5 },
          { name: "广场舞", icon: "💃", met: 5.0 },
          { name: "太极拳", icon: "🧘", met: 3.0 },
          { name: "椭圆机", icon: "🏋️", met: 5.0 },
          { name: "爬楼梯", icon: "🏢", met: 6.0 },
          { name: "跳绳", icon: "⏱️", met: 10.0 },
          { name: "球类运动", icon: "⚽", met: 6.0 },
          { name: "划船机", icon: "🚣", met: 7.0 }
        ]
      },
      {
        category: "抗阻训练",
        types: [
          { name: "哑铃训练", icon: "💪", met: 3.5 },
          { name: "杠铃训练", icon: "🏋️", met: 4.0 },
          { name: "器械训练", icon: "🔧", met: 3.5 },
          { name: "弹力带", icon: "🧵", met: 3.0 },
          { name: "俯卧撑", icon: "🙇", met: 3.5 },
          { name: "深蹲", icon: "🧎", met: 3.5 },
          { name: "仰卧起坐", icon: "🧍", met: 3.0 },
          { name: "引体向上", icon: "🧗", met: 4.0 },
          { name: "卧推", icon: "🏋️", met: 3.5 },
          { name: "壶铃", icon: "🔔", met: 4.0 },
          { name: "爆发力训练", icon: "⚡", met: 6.0 }
        ]
      },
      {
        category: "柔韧与平衡",
        types: [
          { name: "瑜伽", icon: "🧘‍♀️", met: 2.5 },
          { name: "八段锦", icon: "🧍‍♂️", met: 2.5 },
          { name: "拉伸", icon: "🤸", met: 2.0 },
          { name: "静态伸展", icon: "🧠", met: 1.5 },
          { name: "动态伸展", icon: "🤸‍♂️", met: 2.5 },
          { name: "平衡训练", icon: "🧍‍♀️", met: 2.5 },
          { name: "关节活动度训练", icon: "🔄", met: 2.0 },
          { name: "舒展运动", icon: "🌈", met: 2.0 }
        ]
      }
    ];
    
    this.setData({
      categorizedExerciseTypes: exerciseTypesData 
    });
    
    // 生成扁平化的列表用于兼容现有功能
    const allTypes = [];
    const allIcons = [];
    
    exerciseTypesData.forEach(category => {
      category.types.forEach(type => {
        allTypes.push(type.name);
        allIcons.push(type.icon);
      });
    });
    
    this.setData({
      exerciseTypes: allTypes,
      exerciseTypeIcons: allIcons
    });
    
    // 推断当前类别
    this.updateInferredCategory();
  },
  
  /**
   * 更新推断的运动类别
   */
  updateInferredCategory: function() {
    const { exerciseTypeIndex, exerciseTypes } = this.data;
    if (exerciseTypes.length > 0) {
      const exerciseType = exerciseTypes[exerciseTypeIndex];
      const inferredCategory = this.inferExerciseCategory(exerciseType);
      
      this.setData({
        inferredCategory: inferredCategory
      });
    }
  },

  /**
   * 运动类型选择改变
   */
  exerciseTypeChange: function (e) {
    this.setData({
      exerciseTypeIndex: e.detail.value
    });
    
    // 根据选择的运动类型推断运动类别
    this.updateInferredCategory();
    
    // 重新计算卡路里
    this.calculateCalories();
  },

  /**
   * 设置当前日期为默认日期
   */
  setCurrentDate: function () {
    const today = new Date();
    const year = today.getFullYear();
    const month = (today.getMonth() + 1).toString().padStart(2, '0');
    const day = today.getDate().toString().padStart(2, '0');
    const currentDate = `${year}-${month}-${day}`;
    
    const hours = today.getHours().toString().padStart(2, '0');
    const minutes = today.getMinutes().toString().padStart(2, '0');
    const currentTime = `${hours}:${minutes}`;

    this.setData({
      exerciseDate: currentDate,
      startTime: currentTime
    });
  },

  /**
   * 获取运动数据（编辑模式）
   */
  getExerciseData: async function (id) {
    this.setData({ loading: true });
    
    try {
      const response = await api.exercise.getExerciseById(id);
      
      if (response.success && response.data) {
        const exerciseData = response.data;
        
        // 查找类型索引
        const typeIndex = this.data.exerciseTypes.findIndex(type => type === exerciseData.type);
        
        this.setData({
          exerciseTypeIndex: typeIndex >= 0 ? typeIndex : 0,
          exerciseDate: exerciseData.date.split('T')[0], // 提取日期部分
          startTime: exerciseData.startTime,
          duration: exerciseData.duration,
          intensity: exerciseData.intensity,
          caloriesBurned: exerciseData.caloriesBurned.toString(),
          enableGlucoseMonitoring: exerciseData.glucoseBefore !== undefined && exerciseData.glucoseBefore !== null,
          glucoseBefore: exerciseData.glucoseBefore !== undefined ? exerciseData.glucoseBefore.toString() : '',
          glucoseAfter: exerciseData.glucoseAfter !== undefined ? exerciseData.glucoseAfter.toString() : '',
          notes: exerciseData.notes || ''
        });
      } else {
        wx.showToast({
          title: '获取运动数据失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('获取运动数据失败:', error);
      wx.showToast({
        title: '获取运动数据失败',
        icon: 'none'
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  /**
   * 日期选择改变
   */
  dateChange: function (e) {
    this.setData({
      exerciseDate: e.detail.value
    });
  },

  /**
   * 开始时间选择改变
   */
  startTimeChange: function (e) {
    this.setData({
      startTime: e.detail.value
    });
  },

  /**
   * 减少持续时间
   */
  decreaseDuration: function () {
    let duration = this.data.duration;
    if (duration > 5) {
      duration -= 5;
      this.setData({ duration });
      this.calculateCalories();
    }
  },

  /**
   * 增加持续时间
   */
  increaseDuration: function () {
    let duration = this.data.duration;
    duration += 5;
    this.setData({ duration });
    this.calculateCalories();
  },

  /**
   * 持续时间输入
   */
  durationInput: function (e) {
    const duration = parseInt(e.detail.value) || 0;
    this.setData({ duration });
    this.calculateCalories();
  },

  /**
   * 强度滑块改变
   */
  intensityChange: function (e) {
    this.setData({
      intensity: e.detail.value
    });
    this.calculateCalories();
  },

  /**
   * 计算卡路里消耗
   */
  calculateCalories: function() {
    // 只有当所有必要数据都存在时才计算
    if (!this.data.exerciseTypes.length || this.data.exerciseTypeIndex === undefined) {
      return;
    }
    
    const exerciseType = this.data.exerciseTypes[this.data.exerciseTypeIndex];
    const duration = parseFloat(this.data.duration) || 30;
    const intensity = parseFloat(this.data.intensity) || 5;
    const weight = parseFloat(this.data.weight) || 65;
    
    // 构建用户资料对象
    const userProfile = {
      age: this.data.age,
      gender: this.data.gender,
      height: this.data.height,
      exerciseFrequency: this.data.exerciseFrequency
    };
    
    try {
      // 调用计算函数
      const calories = api.exercise.calculateCalories(
        exerciseType, 
        duration, 
        intensity, 
        weight,
        userProfile
      );
      
      // 设置到界面
      this.setData({
        caloriesBurned: calories
      });
      
      console.log(`卡路里计算: ${exerciseType}, ${duration}分钟, 强度${intensity}, 体重${weight}kg, 结果: ${calories}卡`);
    } catch (error) {
      console.error('卡路里计算失败:', error);
    }
  },

  /**
   * 卡路里输入改变
   */
  caloriesInput: function (e) {
    this.setData({
      caloriesBurned: e.detail.value
    });
  },

  /**
   * 切换血糖监测
   */
  toggleGlucoseMonitoring: function (e) {
    this.setData({
      enableGlucoseMonitoring: e.detail.value
    });
  },

  /**
   * 运动前血糖输入
   */
  glucoseBeforeInput: function (e) {
    this.setData({
      glucoseBefore: e.detail.value
    });
  },

  /**
   * 运动后血糖输入
   */
  glucoseAfterInput: function (e) {
    this.setData({
      glucoseAfter: e.detail.value
    });
  },

  /**
   * 备注输入
   */
  notesInput: function (e) {
    this.setData({
      notes: e.detail.value
    });
  },

  /**
   * 取消
   */
  onCancel: function () {
    wx.navigateBack({
      delta: 1
    });
  },

  /**
   * 保存
   */
  onSave: async function () {
    const {
      id,
      exerciseTypeIndex,
      exerciseTypes,
      exerciseDate,
      startTime,
      duration,
      intensity,
      caloriesBurned,
      enableGlucoseMonitoring,
      glucoseBefore,
      glucoseAfter,
      inferredCategory
    } = this.data;

    // 表单验证
    if (!exerciseDate) {
      wx.showToast({
        title: '请选择运动日期',
        icon: 'none'
      });
      return;
    }

    if (!startTime) {
      wx.showToast({
        title: '请选择开始时间',
        icon: 'none'
      });
      return;
    }

    if (!duration || duration <= 0) {
      wx.showToast({
        title: '请输入有效的持续时间',
        icon: 'none'
      });
      return;
    }

    if (!caloriesBurned) {
      wx.showToast({
        title: '请输入卡路里消耗',
        icon: 'none'
      });
      return;
    }

    if (enableGlucoseMonitoring) {
      if (!glucoseBefore) {
        wx.showToast({
          title: '请输入运动前血糖值',
          icon: 'none'
        });
        return;
      }
      if (!glucoseAfter) {
        wx.showToast({
          title: '请输入运动后血糖值',
          icon: 'none'
        });
        return;
      }
    }

    // 构建要保存的数据
    const exerciseData = {
      type: exerciseTypes[exerciseTypeIndex],
      date: exerciseDate,
      startTime: startTime,
      duration: parseInt(duration),
      intensity: parseInt(intensity),
      caloriesBurned: parseFloat(caloriesBurned),
      category: this.data.exerciseCategories[inferredCategory]
    };
    
    // 添加血糖数据（如果启用）
    if (enableGlucoseMonitoring) {
      exerciseData.glucoseBefore = parseFloat(glucoseBefore);
      exerciseData.glucoseAfter = parseFloat(glucoseAfter);
    }

    this.setData({ loading: true });
    
    try {
      let response;
      
      if (id) {
        // 编辑模式：更新现有记录
        response = await api.exercise.updateExercise(id, exerciseData);
      } else {
        // 添加模式：添加新记录
        response = await api.exercise.createExercise(exerciseData);
      }
      
      if (response.success) {
        wx.showToast({
          title: '保存成功',
          icon: 'success',
          duration: 2000,
          success: function() {
            // 延迟导航回上一页，让用户看到成功提示
            setTimeout(() => {
              wx.navigateBack({
                delta: 1
              });
            }, 1500);
          }
        });
      } else {
        wx.showToast({
          title: response.message || '保存失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('保存失败', error);
      wx.showToast({
        title: '保存失败，请重试',
        icon: 'none'
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  /**
   * 获取用户完整资料
   */
  getUserProfile: async function() {
    try {
      const response = await api.getUserProfile();
      if (response && response.success && response.data) {
        const userProfile = response.data;
        
        // 设置用户基本信息
        this.setData({
          weight: userProfile.weight || 65,
          height: userProfile.height || 170,
          age: userProfile.age || 40,
          gender: userProfile.gender || 'male',
          // 判断用户运动频率
          exerciseFrequency: this.determineExerciseFrequency(userProfile)
        });
        
        // 重新计算卡路里
        this.calculateCalories();
      }
    } catch (error) {
      console.error('获取用户资料失败:', error);
    }
  },
  
  /**
   * 根据用户历史运动记录判断运动频率
   */
  determineExerciseFrequency: function(userProfile) {
    // 如果用户有运动历史数据，可以从中判断
    // 这里使用简化的逻辑 - 实际实现可能需要查询历史运动记录
    if (userProfile.exerciseFrequency) {
      return userProfile.exerciseFrequency;
    }
    
    // 默认为偶尔锻炼
    return 'occasional';
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})